package com.ldzhao.blog.util;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectRequest;
import com.ldzhao.blog.model.entity.ArticleContent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;

@Slf4j
public class AliyunOSSUtil {

    private static String endpoint = "oss-cn-hangzhou-internal.aliyuncs.com";
    private static String accessKeyId = "";
    private static String accessKeySecret = "";

    private static String bucketName = "";
    private static String blog_bucketName = "";

    public static void upload(String path, File file) throws IOException {
        OSS client = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        try {
            client.putObject(new PutObjectRequest(bucketName, path, file));
        } catch (Exception e) {
            log.error("上传阿里云对象存储服务器失败", e);
        } finally {
            client.shutdown();
        }
    }

    public static void upload(String path, String content) throws Exception {
        OSS client = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        try {
            client.putObject(new PutObjectRequest(blog_bucketName, path, new ByteArrayInputStream(content.getBytes())));
        } finally {
            client.shutdown();
        }
    }

    public static boolean upload(Long id, String html, String markdown) throws IOException {
        try {
            if (!StringUtils.isEmpty(html)) {
                upload("html/" + id, html);
            }
            if (!StringUtils.isEmpty(markdown)) {
                upload("markdown/" + id, markdown);
            }
        } catch (Exception e) {
            log.error("上传阿里云对象存储服务器失败", e);
            return false;
        }
        return true;
    }

    public static boolean upload(ArticleContent articleContent) throws IOException {
        return upload(articleContent.getId(), articleContent.getContent(), articleContent.getContentMd());
    }
}